package com.dk.controller;

import com.dk.mapper.TabUserMapper;
import com.dk.mapper.UserMapper;
import com.dk.pojo.TabUser;
import com.dk.pojo.User;
import com.dk.service.RoleUserService;
import com.dk.service.UserService;
import com.dk.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

@Controller
@RequestMapping("registerController")
public class RegisterController {
    @Autowired
    TabUserMapper tabUserMapper;
    @Autowired
    RoleUserService roleUserService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserService userService;

    @RequestMapping("register")
    @ResponseBody
    public Integer register(String check,HttpServletRequest request,User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        HttpSession session = request.getSession();
        String username = user.getUsername();
        User user_register = userMapper.selectByUserName(username);
        if (user_register!=null){
            return 2;//员工存在
        }

        String checkCode = (String) session.getAttribute("check_code");
        if (check!=null&&check.equalsIgnoreCase(checkCode)){
            String password = user.getPassword();
            String encryptedPwd = MD5Utils.getEncryptedPwd(password);
            user.setPassword(encryptedPwd);
            int i = userMapper.insertSelective(user);
            Integer uid = user.getUid();
            //指定员工默认角色
            roleUserService.insertDefaultRoleForUser(uid);

            return 1;
        }

        return 0;
    }
    @RequestMapping("isUserNameExists")
    @ResponseBody
    public Integer register(String username){
        User user = userMapper.selectByUserName(username);
        if (user!=null){
            return 1;//用户已存在
        }
        return 2;

    }
}
